name: Add label on docstrings edit

on:
  pull_request_target:
    paths:
      - "haystack/**/*.py"

env:
  PYTHON_VERSION: "3.11"

jobs:
  label:
    runs-on: ubuntu-latest

    steps:
      - name: Checkout base commit
        uses: actions/checkout@v4
        with:
          ref: ${{ github.base_ref }}

      - name: Copy file
        # We copy our script after base ref checkout so we keep executing
        # the same version even after checking out the HEAD ref.
        # This is done to prevent executing malicious code in forks' PRs.
        run: cp .github/utils/docstrings_checksum.py "${{ runner.temp }}/docstrings_checksum.py"

      - name: Setup Python
        uses: actions/setup-python@v5
        with:
          python-version: "${{ env.PYTHON_VERSION }}"

      - name: Get docstrings
        id: base-docstrings
        run: |
          CHECKSUM=$(python "${{ runner.temp }}/docstrings_checksum.py" --root "${{ github.workspace }}")
          echo "checksum=$CHECKSUM" >> "$GITHUB_OUTPUT"

      - name: Checkout HEAD commit
        uses: actions/checkout@v4
        with:
          ref: ${{ github.event.pull_request.head.ref }}
          # This must be set to correctly checkout a fork
          repository: ${{ github.event.pull_request.head.repo.full_name }}

      - name: Get docstrings
        id: head-docstrings
        run: |
          CHECKSUM=$(python "${{ runner.temp }}/docstrings_checksum.py" --root "${{ github.workspace }}")
          echo "checksum=$CHECKSUM" >> "$GITHUB_OUTPUT"

      - name: Check if we should label
        id: run-check
        run: echo "should_run=${{ steps.base-docstrings.outputs.checksum != steps.head-docstrings.outputs.checksum }}" >> "$GITHUB_OUTPUT"

      - name: Add label
        if: ${{ steps.run-check.outputs.should_run == 'true' }}
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: gh pr edit ${{ github.event.pull_request.html_url }} --add-label "type:documentation"
